#include "messagetoast.h"
#include "ui_messagetoastwidget.h"
#if (QT_VERSION < QT_VERSION_CHECK(6, 0, 0))
#include <QApplication>
#include <QDesktopWidget>
#endif

#include <QScreen>
#include <QDebug>

MessageToastWidget::MessageToastWidget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::MessageToastWidget)
{
    ui->setupUi(this);
}

MessageToastWidget::~MessageToastWidget()
{
    delete ui;
}


void MessageToastWidget::setToastText(const QString& text)
{
    ui->label->setText(text);
}



MessageToast &MessageToast::instance()
{
    static MessageToast ins;
    return ins;
}
 
MessageToast::MessageToast()
{
    mDialog = new BaseShadowDialog();
    mToastWidget = new MessageToastWidget(mDialog);
    mDialog->setMainWidget(mToastWidget);
    mDialog->setBaseSize( 266, 42);
    mDialog->setWindowFlags(mDialog->windowFlags() | Qt::WindowStaysOnTopHint | Qt::Tool);


//#if (QT_VERSION < QT_VERSION_CHECK(6, 0, 0))
//    QDesktopWidget *pDesktop = QApplication::desktop();
//    mDialog->move((pDesktop->width() - 266) / 2, 50);
//#else
//    mDialog->move((window()->screen()->geometry().width() - 266) / 2, 50);
//#endif
}

MessageToast::~MessageToast()
{
    delete mDialog;
}
 
void MessageToast::show(MessageToast::Level level, const QString &text)
{
    QScreen* screen = qApp->primaryScreen();
    QPoint pos = screen->geometry().topLeft() + QPoint((screen->geometry().width() - 266) / 2, 50);
    mDialog->move(pos);
    qDebug() << "toast show screen:" << screen->geometry() << " dialog:" << mDialog->pos();

    mToastWidget->setToastText(text); // level
    mDialog->show();
    if (mTimerId != 0)
    {
        killTimer(mTimerId);
    }
    mTimerId = startTimer(3000);
}
 
void MessageToast::timerEvent(QTimerEvent *event)
{
    killTimer(mTimerId);
    mTimerId = 0;
    mDialog->hide();
}
